let layer = layui.layer
initArticleList()
let indexAdd = null
let indexEdit = null
let form = layui.form


function initArticleList() {
    $.ajax({
        method: 'GET',
        url: '/my/article/cates',
        success: function (res) {
            if (res.status !== 0) {
                return layer.msg('获取文章列表失败')
            }
            $('tbody').html(template('tpl-table', res))
        }
    })
}

$('#btnAddcate').click(function () {
    indexAdd = layer.open({
        title: '添加文章类别',
        type: 1,
        area: ['500px', '250px'],
        content: $('#dialog-add').html()
    })
})

$('body').on('submit', '#form-add', function (e) {
    e.preventDefault()
    $.ajax({
        method: 'POST',
        url: '/my/article/addcates',
        data: $(this).serialize(),
        success: function (res) {
            if (res.status !== 0) {
                return layer.msg('新增分类失败！')
            }
            layer.msg('新增分类成功！')
            initArticleList()
            layer.close(indexAdd)
        }
    })
})

$('tbody').on('click', '#btnEdit', function () {
    indexEdit = layer.open({
        title: '修改文章类别',
        type: 1,
        area: ['500px', '250px'],
        content: $('#dialog-edit').html()
    })
    $.ajax({
        method: 'GET',
        url: `/my/article/cates/${$(this).attr('data-id')}`,
        success: function (res) {
            console.log(res);
            form.val("form-edit", res.data)
        }
    })
})

$('body').on('submit', '#form-edit', function (e) {
    e.preventDefault()
    $.ajax({
        method: 'POST',
        url: '/my/article/updatecate',
        data: $(this).serialize(),
        success: function (res) {
            if (res.status !== 0) {
                return layer.msg('更新数据失败！')
            }
            layer.msg('更新数据成功！')
            layer.close(indexEdit)
            initArticleList()
        }
    })
})

$('tbody').on('click', '#btn-delete', function () {
    let id = $(this).attr('data-id')
    layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
        $.ajax({
            method: 'GET',
            url: `/my/article/deletecate/${id}`,
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg('删除分类失败!')
                }
                layer.msg('删除分类成功！')
                initArticleList()
            }
        })
        layer.close(index)
    });
})